<?php
// 登录处理脚本
require_once 'db_config.php';

// 检查请求方法是否为POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $remember = isset($_POST['remember']);
    
    $errors = [];
    
    // 验证输入
    if (empty($username)) {
        $errors['username'] = '请输入用户名或邮箱';
    }
    
    if (empty($password)) {
        $errors['password'] = '请输入密码';
    }
    
    // 如果有错误，返回JSON错误信息
    if (!empty($errors)) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'errors' => $errors]);
        exit;
    }
    
    // 准备SQL查询，使用预处理语句防止SQL注入
    $sql = "SELECT id, username, email, password_hash FROM users WHERE username = ? OR email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $username, $username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        
        // 验证密码
        if (password_verify($password, $user['password_hash'])) {
            // 密码验证成功，开始会话
            session_start();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            setcookie('login_user', $user['username']);
            // 如果勾选"记住我"，设置持久化Cookie
            if ($remember) {
                $token = bin2hex(random_bytes(16));
                setcookie('remember_token', $token, time() + 30 * 24 * 3600, '/', '', true, true);
                
                // 这里应该将token存储到数据库中
                // $updateTokenSql = "UPDATE users SET remember_token = ? WHERE id = ?";
                // $updateStmt = $conn->prepare($updateTokenSql);
                // $updateStmt->bind_param("si", $token, $user['id']);
                // $updateStmt->execute();
            }
            
            // 返回成功响应
            header('Content-Type: application/json');
            echo json_encode([
                'status' => 'success',
                'message' => '登录成功',
                'redirect' => '../lt/index.php' // 登录后重定向的页面
            ]);
            exit;
        } else {
            $errors['password'] = '密码错误';
        }
    } else {
        $errors['username'] = '用户名或邮箱不存在';
    }
    
    // 返回错误信息
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'errors' => $errors]);
    exit;
} else {
    // 不是POST请求，返回错误
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => '无效的请求方法']);
    exit;
}
?>
